//
//  BGOriginalPicView.swift
//  WeiboSwift
//
//  Created by 战场原黑仪 on 16/7/26.
//  Copyright © 2016年 战场原黑仪. All rights reserved.
//

import UIKit

private let BGStatusPicViewCellID = "BGStatusPicViewCellID"

class BGOriginalPicView: UICollectionView {

    //模型
    var picsModel: [BGHomePictureModel]?{
        didSet{
            // 获得当前配图的size
            let size = getPictureViewSize(picsModel?.count ?? 0)
            
            // 更新当前配图的约束
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(size)
            }
            // 刷新UI
            reloadData()
        }
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        self.backgroundColor = self.superview?.backgroundColor
        
        //获取layout
        let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        flowLayout.itemSize = CGSize(width: itemWH_S, height: itemWH_S)
        flowLayout.minimumLineSpacing = itemMargin_S
        flowLayout.minimumInteritemSpacing = itemMargin_S
        
        self.registerClass(BGOriginalPicCell.self, forCellWithReuseIdentifier: BGStatusPicViewCellID)
        
        dataSource = self
    }
    
}

//MARK: - 数据源代理方法
extension BGOriginalPicView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.picsModel?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(BGStatusPicViewCellID, forIndexPath: indexPath) as! BGOriginalPicCell
        
        cell.pic_url = self.picsModel![indexPath.item]
        
        return cell
    }
    
}

//MARK: - 图片设置
extension BGOriginalPicView {
    
    private func getPictureViewSize(count: Int) -> CGSize {
        // 计算出行数和列数
        let col = count == 4 ? 2 : count >= 3 ? 3 : count
        let row = count == 4 ? 2 : (count - 1)/3 + 1
        // 计算size 中的宽和高
        let w = CGFloat(col) * itemWH_S + CGFloat(col - 1)*itemMargin_S
        let h = CGFloat(row) * itemWH_S + CGFloat(row - 1)*itemMargin_S
        
        return CGSize(width: w, height: h)
    }
    
}
